
const tagsView = {
  state: {
    visitedViews: []
  },
  mutations: {
    ADD_VISITED_VIEWS: (state, view) => {
      if (!state.visitedViews.some(v => v.path === view.path)) {
        state.visitedViews.push(
          Object.assign({}, view, {
            // title: view.path// view.meta.title || 'no-name'
            title: view.meta.title || 'no-name'
          })
        )
      }
    },
    DEL_VISITED_VIEWS: (state, view) => {
      if (state.visitedViews.length === 1 && state.visitedViews[0].path === '/index') {
        return
      }
      for (let [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews.splice(i, 1); // 从数组的第i个元素开始，向后删除1个元素
          break
        }
      }
    },
    DEL_OTHERS_VIEWS: (state, view) => {
      for (let [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews = state.visitedViews.slice(i, i + 1) // slice从数组中返回给定的元素
          break
        }
      }
    },
    DEL_ALL_VIEWS: (state) => {
      if (state.visitedViews.length === 1 && state.visitedViews[0].path === '/index') {
        return
      }
      state.visitedViews = []
    }
  },
  actions: {
    addVisitedViews ({commit}, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delView ({commit, state}, view) {
      let index = -1
      for (let [i, v] of Array.from(state.visitedViews).entries()) {
        if (v.path === view.path) {
          index = i
          break
        }
      }
      return new Promise(resolve => {
        commit('DEL_VISITED_VIEWS', view)
        resolve({
          curIndex: index,
          visitedViews: [...state.visitedViews]
        })
      })
    },
    delOthersView ({commit}, view) {
      return new Promise(resolve => {
        commit('DEL_OTHERS_VIEWS', view)
        resolve()
      })
    },
    delAllViews ({commit}) {
      return new Promise(resolve => {
        commit('DEL_ALL_VIEWS')
        resolve()
      })
    }
  }
}

export default tagsView
